package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.Role;
import cn.kgc.vue.entity.RolePermission;
import cn.kgc.vue.entity.UserRole;
import cn.kgc.vue.mapper.PermissionMapper;
import cn.kgc.vue.mapper.RoleMapper;
import cn.kgc.vue.mapper.RolePermissionMapper;
import cn.kgc.vue.mapper.UserRoleMapper;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-09-25 13:56:50
*/
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{


    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult rolePage(QueryCondition<Role> queryCondition) {

        Page<Role> rolePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        Role searchParams = queryCondition.getSearchParams();
        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        lambda.like(StringUtils.isNotBlank(searchParams.getRoleCh()),Role::getRoleCh,searchParams.getRoleCh())
                .like(StringUtils.isNotBlank(searchParams.getRoleEn()),Role::getRoleEn,searchParams.getRoleEn())
                .orderByDesc(Role::getCreateTime);

        baseMapper.selectPage(rolePage,lambda);

        return ResponseResult.success()
                .data("total",rolePage.getTotal())
                .data("tableData",rolePage.getRecords());

    }

    @Override
    public ResponseResult removeRole(Integer id) {

        // 1. 判定删除的角色是否被占用
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId,id);

        List<UserRole> userRoles = userRoleMapper.selectList(lambda);

        if (ObjectUtils.isNotNull(userRoles)){
            return  ResponseResult.fail().message("角色被占用");
        }
        // 2. 删除角色
        baseMapper.deleteById(id);
        // 3. 删除角色和权限的关联信息
        LambdaQueryWrapper<RolePermission> lambda1 = new QueryWrapper<RolePermission>().lambda();
        lambda1.eq(RolePermission::getRoleId,id);
        rolePermissionMapper.delete(lambda1);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult rolePermissions(Integer id) {

        // 角色id 根据角色id  查询权限id   sys_role_permission
        LambdaQueryWrapper<RolePermission> lambda = new QueryWrapper<RolePermission>().lambda();
        lambda.eq(RolePermission::getRoleId,id);

        List<Integer> pIds = rolePermissionMapper.selectList(lambda).stream()
                .map(rp -> rp.getPerId())
                .collect(Collectors.toList());
        List<Integer> defaultPids = null;
        if (ObjectUtils.isNotNull(pIds)){
            defaultPids  = permissionMapper.selectBatchIds(pIds).stream()
                    .filter(p -> p.getIsMenu() == 2)
                    .map(p -> p.getId())
                    .collect(Collectors.toList());
        }

        return ResponseResult.success().data("permissionList",defaultPids);
    }

    @Override
    public ResponseResult addPermissions(Map<String, Object> params) {

        // newKeys,rid
        List<Integer> newKeys = (List<Integer>) params.get("newKeys");
        Integer rid = (Integer) params.get("rid");

        // 根据角色id  删除原有的权限
        LambdaQueryWrapper<RolePermission> lambda = new QueryWrapper<RolePermission>().lambda();
        lambda.eq(RolePermission::getRoleId,rid);
        rolePermissionMapper.delete(lambda);

        // 遍历newKeys
        newKeys.forEach(pid->{
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPerId(pid);
            rolePermission.setRoleId(rid);
            rolePermissionMapper.insert(rolePermission);
        });



        return ResponseResult.success().message("权限分配成功");
    }
}




